package vn.gq.app4vn.doctruyen;


import org.json.JSONObject;

import vn.gq.cd.model.bean.AdmobItem;
import vn.gq.tym.utils.Client;
import vn.gq.tym.utils.DataType;
import vn.gq.tym.utils.IClientListener;
import vn.gq.tym.utils.NetworkOption;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class SplashActivity extends FragmentActivity {
	
	private static final int SPLASH_COUNT_TIME = 2000;
	private boolean actived = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		
		((ImageView) findViewById(R.id.splash)).setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				actived = true;
				return true;
			}
		});
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				int waited = 0;
				while((waited <= SPLASH_COUNT_TIME) && !actived) {
					waited += 100;
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
				startActivity(intent);
				finish();
			}
		}).start();
		
		Client client = new Client(getApplicationContext());
		client.setCacheTime(3600000); // cache in 1 hour
		client.setNetworkOption(NetworkOption.OPTION_USE_CACHE);
		client.setOutputDataType(DataType.JSON);
		client.executeAndListener(String.format("http://apps.cucdinh.vn/ads/admob?id=%s&t=text", getPackageName()), new IClientListener() {
			
			@Override
			public void onDone(int code, Object result) {
				if (BuildConfig.DEBUG) {
					Log.e("longhoanggiang", String.valueOf(result));
				}
				AdmobItem admobItem = null;
				if (result != null) {
					try {
						admobItem = new AdmobItem((JSONObject) result);
						admobItem.setLoaded(true);
						admobItem.setPreference(getApplicationContext());
					} catch(Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
		
	}

}
